import datetime
import sys
import os

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','modules')))
import mods


def index(req):
	web = mods.Web(req)

	dbConnection = mods.GetDBConnection()
	cursor = dbConnection.cursor()

	ticketDone = web.GetNumber('ticket_done')

	if web.user.admin:
		if ticketDone:
			ticket = mods.Ticket(ticketDone)
			ticket.completeDate = datetime.datetime.now()
			ticket.completeBy = web.user.openID
			ticket.done = True
			ticket.Save()



	web.Header()

	if web.user.admin:
		web.Write("""<h2>Location Tickets</h2>""")

		#Outstanding tickets
		cursor.execute("SELECT id FROM tickets WHERE (done = FALSE) ORDER BY report_date DESC")
		if cursor.rowcount:
			web.Write("""<table class="grid">""")
			web.Write("""<tr><th>Date</th><th>User</th><th>Location</th><th>Request</th><th>Done</th></tr>""")
			for record in cursor.fetchall():
				(ticketID, ) = record
				ticket = mods.Ticket(ticketID)
				web.Write("<tr>")
				
				web.Write("""<td style="text-align: left;">%s</td>""" % (ticket.reportDate.strftime("%Y-%m-%d %H:%M")))

				location = mods.Location(ticket.locationID)
				web.Write("""<td><a href="/locations/index.py?id=%s">%s</a></td>""" % (location.id, location.engName))

				reporter = mods.User(ticket.reportBy)
				web.Write("""<td style="text-align: left;">%s</td>""" % (reporter.name))

				web.Write("""<td style="text-align: left;">%s</td>""" % (ticket.message))

				web.Write("""<td><a href="/locations/tickets.py?ticket_done=%s">Done</a></td>""" % (ticket.id, ))

				web.Write("</tr>")
			web.Write("</table>")

	web.Write("""<br />""")

	web.Footer()


